<?php
/**
 * 订单退款同步请求
 * @author ome
 * @access public
 * @copyright www.shopex.net.cn 2010
 *
 */
class ome_rpc_request_refund extends ome_rpc_request {
    
    //退款状态
    var $status = array(
          'succ'=>'SUCC',
          'failed'=>'FAILED',
          'cancel'=>'CANCEL',
          'error'=>'ERROR',
          'invalid'=>'INVALID',
          'progress'=>'PROGRESS',
          'timeout'=>'TIMEOUT',
          'ready'=>'READY',
    );
    
    /**
     * 添加交易退款单
     * @access public
     * @param int $refund_id 退款单主键ID
     * @return boolean
     */
    public function add($refund_id){

        if(!empty($refund_id)){
            
            $params = $this->refund_request_params($refund_id,'');
            $shop_id = $params['shop_id'];
            if($shop_id){
                $shop_info = &app::get('ome')->model('shop')->dump($shop_id,'name');
                $title = '店铺('.$shop_info['name'].')添加[交易退款单(金额:'.$params['refund_fee'].')](订单号:'.$params['tid'].'退款单号:'.$params['refund_id'].')';
            }else{
                return false;
            }
            
            $callback = array(
                'class' => 'ome_rpc_request_refund',
                'method' => 'refund_add_callback',
            );

            $this->request('store.trade.refund.add',$params,$callback,$title,$shop_id);
            kernel::log("退款测试.....");
        }else{
            return false;
        }

    }
    
    function refund_add_callback($result){
        return $this->callback($result);
    }
    
    /**
     * 交易退款单请求
     * @access public
     * @param mixed $sdf 退款请求数据
     * @return boolean
     */
    public function refund_request($sdf=NULL){
       
        if(!empty($sdf)){
                
            $params = $this->refund_request_params('',$sdf);
            $shop_id = $params['shop_id'];
            if($shop_id){
                $shop_info = &app::get('ome')->model('shop')->dump($shop_id,'name');
                $title = '店铺('.$shop_info['name'].')发起交易退款请求(金额:'.$params['refund_fee'].',支付方式:'.$params['payment_type'].')]订单号:'.$params['tid'];
            }else{
                return false;
            }
            
            $callback = array(
                'class' => 'ome_rpc_request_refund',
                'method' => 'refund_request_callback',
            );
            $this->request('store.trade.refund.add',$params,$callback,$title,$shop_id);
        }else{
            return false;
        }
    }
    
    function refund_request_callback($result){
        
        $status = $result->get_status();
        $oOrder = &app::get('ome')->model('orders');
        $oApi_log = &app::get('ome')->model('api_log');
        $oLoger =  &app::get('ome')->model('operation_log');
        $oRefaccept = &app::get('ome')->model('refund_apply');
        
        $callback_params = $result->get_callback_params();
        $log_id = $callback_params['log_id'];
        $apilog_detail = $oApi_log->dump(array('log_id'=>$log_id), 'params');
        $apilog_detail = unserialize($apilog_detail['params']);
        $params=$apilog_detail[1];
        $order_bn = $params['tid'];
        $shop_id = $params['shop_id'];
        $refund_apply_id = $params['refund_apply_id'];
        $order_detail = $oOrder->dump(array('order_bn'=>$order_bn,'shop_id'=>$shop_id), 'order_id,payed,pay_status');
        
        
        if ($status != 'succ'){
           
            $oOperation_log = &app::get('ome')->model('operation_log');
           
            
          
            $order_id = $order_detail['order_id'];
            //状态回滚，变成已支付/部分付款/部分退款
            kernel::single('ome_order_func')->update_order_pay_status($order_id);
            $oRefaccept->update(array('status'=>'6'), array('apply_id'=>$refund_apply_id));
            //操作日志
            $oOperation_log->write_log('order_refund@ome',$order_id,'订单:'.$order_bn.'发起退款请求,前端拒绝退款，退款失败');
        }else{
        	
        	$apply_id=$params['refund_apply_id'];
        	$apply_detail = $oRefaccept->refund_apply_detail($apply_id);
        	 
        	if (in_array($apply_detail['status'],array('2','5','6')))
        	{
        		$oRefund = &app::get('ome')->model('refunds');
        		
        		//查找本申请是否是与售后相关的，如果相关，则检查并回写数据
        		$oretrun_refund_apply =&app::get('ome')->model('return_refund_apply');
        		$return_refund_appinfo = $oretrun_refund_apply->dump(array('refund_apply_id'=>$apply_id));
        		if ($return_refund_appinfo['return_id'])
        		{
        			$oreturn = &app::get('ome')->model('return_product');
        			$return_info = $oreturn->product_detail($return_refund_appinfo['return_id']);
        			if (($return_info['refundmoney']+$apply_detail['money'])>$return_info['tmoney'])
        			{
        				$this->end(false, '申请退款金额大于售后的退款金额！');
        			}
        			$return_info['refundmoney'] = $return_info['refundmoney']+$apply_detail['money'];
        			$oreturn->save($return_info);
        			 
        			$oLoger->write_log('return@ome',$return_info['return_id'],"售后退款成功。");
        		}
        		//订单信息更新
        		$orderdata = array();
        		if (round($apply_detail['money'],3)== round(($order_detail['payed']),3))
        		{
        			$orderdata['pay_status'] = 5;
        			//                        //将原来的全额退款的 未发货的订单取消 封装成一个方法check_iscancel
        			//                        $oRefaccept->check_iscancel($apply_detail['order_id'],$apply_detail['memo']);
        		}
        		else
        		{
        			$orderdata['pay_status'] = 4;
        			//                        //部分退款时打回未发货的发货单
        			//                        $oOrder->rebackDelivery($ids,'',true);
        		}
        		$orderdata['order_id'] =  $apply_detail['order_id'];
        		$orderdata['payed'] = $order_detail['payed'] - $apply_detail['money'];
        		$oOrder->save($orderdata);
        		 
        		$oLoger->write_log('order_modify@ome',$orderdata['order_id'],"退款成功，更新订单退款金额。");
        		 
        		//退款申请状态更新
        		$applydata = array();
        		$applydata['apply_id'] = $apply_id;
        		$applydata['status'] = 4;//已经退款
        		$applydata['refunded'] = $apply_detail['money'];// + $order_detail['payinfo']['cost_payment'];
        		$applydata['last_modified'] = time();
        		$oRefaccept->save($applydata,true);
        		$oLoger->write_log('refund_apply@ome',$applydata['apply_id'],"退款成功，更新退款申请状态。");
        		 
        		//更新售后退款金额
//         		$return_id = intval($params['return_id']);
//         		$sql = "UPDATE `sdb_ome_return_product` SET `refundmoney`=IFNULL(`refundmoney`,0)+{$apply_detail['money']} WHERE `return_id`='".$return_id."'";
//         		kernel::database()->exec($sql);
        		 
        		//单据生成：生成退款单
        		$refunddata = array();
        		$refund_apply_bn = $apply_detail['refund_apply_bn'];
        		if ($refund_apply_bn){
        			$refund_bn = $refund_apply_bn;
        		}else{
        			$refund_bn = $oRefund->gen_id();
        		}
        		$refunddata['refund_bn'] = $refund_bn;
        		$refunddata['order_id'] = $apply_detail['order_id'];
        		$refunddata['shop_id'] = $order_detail['shop_id'];
        		$refunddata['account'] = $params['buyer_account'];
        		$refunddata['bank'] = $params['buyer_bank'];
        		$refunddata['pay_account'] = $apply_detail['pay_account'];
        		$refunddata['currency'] = $order_detail['currency'];
        		$refunddata['money'] = $apply_detail['money'];
        		$refunddata['paycost'] = 0;//没有第三方费用
        		$refunddata['cur_money'] = $apply_detail['money'];//汇率计算 TODO:应该为汇率后的金额，暂时是人民币金额
        		$refunddata['pay_type'] = $params['pay_type'];
        		
        		$paymentCfgObj = &app::get('ome')->model('payment_cfg');
        		//支付方式信息
        		$cfg = $paymentCfgObj->dump(array('pay_bn'=>$params['payment_tid']), 'id');
        		$refunddata['payment'] = $cfg['id'];
        		
        
        		$paymethods = ome_payment_type::pay_type();
                $refunddata['paymethod'] = $paymethods[$refunddata['pay_type']];
        		//Todo ：确认paymethod
        		$opInfo = kernel::single('ome_func')->getDesktopUser();
        		$refunddata['op_id'] = $opInfo['op_id'];
        		 
        		$refunddata['t_ready'] = time();
        		$refunddata['t_sent'] = time();
        		$refunddata['status'] = "succ";#支付状态
        		$refunddata['memo'] = $apply_detail['memo'];
        		$oRefund->save($refunddata);
        		//var_dump($oRefund);
        		//更新订单支付状态
        		kernel::single('ome_order_func')->update_order_pay_status($apply_detail['order_id']);
        		 
        		$oLoger->write_log('refund_accept@ome',$refunddata['refund_id'],"退款成功，生成退款单".$refunddata['refund_bn']);
        		 
        		 
        		 
        	}
        }
        return $this->callback($result);
    }
    
    /**
     * 更新交易退款状态
     * @access public
     * @param int $refund_id 退款单主键ID
     * @return boolean
     */
    public function status_update($refund_id){
        
        if(!empty($refund_id)){
            $refundObj = &app::get('ome')->model('refunds');
            $orderObj = &app::get('ome')->model('orders');
            $refund_detail = $refundObj->dump(array('refund_id'=>$refund_id), 'order_id,shop_id,refund_bn,status');
            $order = $orderObj->dump($refund_detail['order_id'], 'order_bn');
            $params['tid'] = $order['order_bn'];
            $params['refund_id '] = $refund_detail['refund_bn'];
            $params['oid '] = '';#子订单id
            $params['status'] = $this->status[$refund_detail['status']];
            
            $callback = array(
                'class' => 'ome_rpc_request_refund',
                'method' => 'refund_status_update_callback',
            );
            
            $shop_id = $refund_detail['shop_id'];
            if($shop_id){
                $shop_info = &app::get('ome')->model('shop')->dump($shop_id,'name');
                $title = '店铺('.$shop_info['name'].')更新[交易退款状态]:'.$params['status'].'(订单号:'.$order['order_bn'].'退款单号:'.$refund_detail['refund_bn'].')';
            }else{
                return false;
            }
            
            $this->request('store.trade.refund.status.update',$params,$callback,$title,$shop_id);
        }else{
            return false;
        }
    }
    
    function refund_status_update_callback($result){
        return $this->callback($result);
    } 
    
    /**
     * 组织退款单发起参数
     * @access private
     * @param number $refund_id 退款单ID
     * @param mixed $sdf 原始请求数据
     * @return ArrayObject 标准请求参数数据 
     */
    private function refund_request_params($refund_id='', $sdf=''){

        $paymentCfgObj = &app::get('ome')->model('payment_cfg');
        $refundObj = &app::get('ome')->model('refunds');
        $orderObj = &app::get('ome')->model('orders');
        $memberObj = &app::get('ome')->model('members');
        
        if (!empty($refund_id)){
            $refund_detail = $refundObj->dump(array('refund_id'=>$refund_id), '*');
            $order_id = $refund_detail['order_id'];
        }elseif($sdf){
            $refund_detail = $sdf;
            $order_id = $refund_detail['order_id'];
            $curr_time = time();
            $refund_detail['t_begin'] = $curr_time;
            $refund_detail['t_end'] = $curr_time;
        }

        //支付方式信息
        $cfg = $paymentCfgObj->dump(array('id'=>$refund_detail['payment']), 'pay_bn,custom_name');
        $refund_detail['pay_bn'] = $cfg['pay_bn'];
        $refund_detail['paymethod'] = $cfg['custom_name'];
        //订单/会员信息
        $order = $orderObj->dump($order_id, 'order_bn,member_id,shop_id');
        $member_info = $memberObj->dump($order['member_id'],'uname,name');

        $params = array();
        $params['shop_id'] = $order['shop_id'];
        $params['tid'] = $order['order_bn'];
        $params['refund_id'] = $refund_detail['refund_bn'];
        $params['refund_apply_id'] = $refund_detail['apply_id'];
        $params['buyer_account'] = $refund_detail['account']?$refund_detail['account']:'';
        $params['buyer_bank'] = $refund_detail['bank']?$refund_detail['bank']:'';
        $params['seller_account'] = $refund_detail['pay_account']?$refund_detail['pay_account']:'';
        $params['buyer_name'] = $member_info['contact']['name'];#买家姓名
        $params['buyer_id'] = $member_info['account']['uname'];#买家会员帐号
        $params['currency'] = $refund_detail['currency']?$refund_detail['currency']:'CNY';
        $params['refund_fee'] = $refund_detail['money'];
        $params['paycost'] = $refund_detail['paycost']?$refund_detail['paycost']:'';
        $params['currency_fee'] = $refund_detail['cur_money'] ? $refund_detail['cur_money'] : $refund_detail['money'];
        $params['pay_type'] = $refund_detail['pay_type'];
        $params['payment_tid'] = $refund_detail['pay_bn'];
        $params['payment_type'] = $refund_detail['paymethod']?$refund_detail['paymethod']:'';
        $refund_detail['t_ready'] = $refund_detail['t_ready'] ? $refund_detail['t_ready'] : time();
        $params['t_begin'] = date("Y-m-d H:i:s",$refund_detail['t_ready']);
        $params['t_sent'] = $refund_detail['t_sent'] ? date("Y-m-d H:i:s",$refund_detail['t_sent']) : '';
        $params['t_received'] = $refund_detail['t_received'] ? date("Y-m-d H:i:s",$refund_detail['t_received']) : date("Y-m-d H:i:s",time());
        $params['status'] = $this->status[$refund_detail['status']];
        $params['memo'] = $refund_detail['memo']?$refund_detail['memo']:'';
        $params['outer_no'] = $refund_detail['trade_no']?$refund_detail['trade_no']:'';
        $params['modify'] = date("Y-m-d H:i:s", time());
        return $params;
    }

}